<?php

namespace app\uniapp\controller;

use app\common\exception\MiException;
use app\model\store\Coupon;
use app\model\store\UserCoupon;
use app\uniapp\service\CouponService;
use app\uniapp\service\UniAuthService;
use app\uniapp\service\UserCouponService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;

class CouponController extends UniController
{

    // 优惠券列表，只能读取有效的领取券，不能读取发放券和无效的券
    // 只能读取所属会员等级的券
    /**
     * @throws DbException
     */
    public function paginate(): \think\response\Json
    {
        $where = [
            ['get_type', '=', 'take'],
        ];
        // todo: 判断会员等级

        $list = CouponService::instance()->query()->where('get_type', 'take')->paginate(20);

        return jsonSuccess([
            'items' => $list->items(),
            'total' => $list->total(),
        ]);

    }

    /**
     * 领取优惠券/领券
     * @throws MiException
     */
    public function get(): \think\response\Json
    {
        if (request()->isPost()){
            Db::transaction(function (){

                $id = $this->post('id');
                $info = Coupon::lock(true)->find($id);
                if (!$info){
                    throw new MiException("优惠券不存在");
                }
                $totalNum = $info->total_num;
                if ($totalNum!=-1 && $totalNum==0){
                    throw new MiException("优惠券数量不足");
                }
                // 判断是否已领取过
                $uc = UserCoupon::where('coupon_id', $id)->where('user_id', UniAuthService::instance()->getLoginId())->lock(true)->find();
                if ($uc){
                    throw new MiException("请勿重复领取");
                }
                // 领取优惠券
                UserCouponService::instance()->createByCouponId($info->id, UniAuthService::instance()->getLoginId());
            });
            return jsonSuccess();
        }else{
            throw new MiException(REQUEST_ERROR);
        }

    }
}
